package com.jt.auth.config;



import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 1)加密对象
 * 2）配置认证规则
 * 当我们执行登录操作时：（了解）
 * 1）Filter(过滤器)
 * 2）AuthenticationManager(认证管理器）
 * 3）AuthenticationProvider(认证服务处理器）
 * 4）UserDetailsService(负责用户信息的获取及封装）
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //初始化加密对象
    //对象提供了一种不可逆的加密方式，相对于md5的方式会更加安全
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证规则
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭跨域攻击
        http.csrf().disable();
        //放行所有资源的访问
        http.authorizeRequests().anyRequest().permitAll();
        //定义登录成功和失败以后的处理逻辑
        http.formLogin()
                .successHandler(successHandler())
                .failureHandler(failureHandler());
    }
    @Bean
    public AuthenticationFailureHandler failureHandler() {
        return (request,response,e)->{
            Map<String,Object> map = new HashMap<>();
            map.put("state", 500);
            map.put("message", "login failure");
            writerJsonToClient(response,map);//把map对象转化成json
        };
    }

    @Bean
    public AuthenticationSuccessHandler successHandler() {
        return (request,response,authentication)->{
            Map<String,Object> map = new HashMap<>();
            map.put("state", 200);
            map.put("message", "login OK");
            writerJsonToClient(response,map);
        };

    }



    private void writerJsonToClient(HttpServletResponse response, Object object) throws IOException {
        String jsonStr = new ObjectMapper().writeValueAsString(object);
        PrintWriter writer = response.getWriter();
        writer.println(jsonStr);
        writer.flush();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }

}
